import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xiaozhou_ams_flutter/tools.dart';
import 'package:xiaozhou_ams_flutter/userprofile/UserCacheManager.dart';
import 'registration_page.dart'; // 引入注册页面
import '../api_client.dart';



class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: const EdgeInsets.only(top: 0),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                'assets/img.png', // Logo图片路径
                height: 84.0, // Logo的高度
              ),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () {
                    _LoginButter("18963764423","123456"); //测试账号
                  },
                  child: const Text('一键登录'),
                ),
              ),
              const SizedBox(height: 16.0),
              const SizedBox(height: 16.0),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: TextField(
                  controller: _usernameController,
                  decoration: const InputDecoration(
                    labelText: '请输入手机号',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.person),
                  ),
                ),
              ),
              const SizedBox(height: 16.0),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: TextField(
                  controller: _passwordController,
                  obscureText: true,
                  decoration: const InputDecoration(
                    labelText: '请输入密码',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.lock),
                  ),
                ),
              ),
              const SizedBox(height: 32.0),
              SizedBox(
                width: double.infinity, // 按钮宽度占满整个屏幕
                child: ElevatedButton(
                  onPressed: () async {
                    //  实现登录逻辑 请求后端接口验证
                    String userPhone = _usernameController.text;
                    String password = _passwordController.text;
                    _LoginButter(userPhone,password);
                  },
                  child: const Text('登 录'),
                ),
              ),
              const SizedBox(height: 16.0),
              SizedBox(
                width: double.infinity, // 按钮宽度占满整个屏幕
                child: ElevatedButton(
                  onPressed: () {
                    // 跳转到注册页面
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const RegistrationPage(),
                      ),
                    );
                  },
                  child: const Text('注 册'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  // 使用正则表达式匹配手机号格式
  bool isValidPhoneNumber(String phoneNumber) {
    RegExp regex = RegExp(r'^1[3456789]\d{9}$');
    return regex.hasMatch(phoneNumber);
  }

  Future<void> _LoginButter(String userPhone, String password) async {
    if (userPhone.isEmpty || password.isEmpty) {
      SnackbarHelper.showToast("账号密码不能为空");
      return;
    }
    if (!isValidPhoneNumber(userPhone)) {
      SnackbarHelper.showToast("请填写正确的手机号码");
      return;
    }

    try {
      final formData = {'phone': userPhone, 'password_hash': password};
      final response = await ApiClient.sendPostRequest('/user/login', formData);
      final jsonMap = json.decode(response!);

      if (jsonMap['success']) {
        final data = jsonMap['data'];
        final String token = data['token'];
        final SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setString('userToken', token);

        if (kDebugMode) {
          print('Login successful!');
        }
        await _getUser();
        Navigator.pushReplacementNamed(context, '/main');
      } else {
        SnackbarHelper.showToast("账号密码错误请重新登录！");
      }
    } catch (error) {
      if (kDebugMode) {
        print('Login failed! Error: $error');
      }
      SnackbarHelper.showToast("系统错误，请联系系统管理员！");
    }
  }

  Future<void> _getUser() async {
    try {
      final response = await ApiClient.sendGetRequest('user/findInfo');
      if(response!=null){
        final jsonMap = json.decode(response);
        final bool success = jsonMap['success'];
        if(success){
          final data = jsonMap['data'];
          if (data['avatarURL'] != null) {
            final avatarPath = await UserCacheManager.cacheAvatar(data['avatarURL']);
            await UserCacheManager.saveUserInfo(
              userId: data['id'].toString(),
              username: data['username'],
              avatarURL: data['avatarURL'],
            );
            if (kDebugMode) {
              print('Avatar is cached at: $avatarPath');
            }
          } else {
            if (kDebugMode) {
              print('No avatar URL provided');
            }
          }
        }
      }else{
        if (kDebugMode) {
          print(response);
        }
        SnackbarHelper.showToast("服务器错误，请联系管理员~！");
      }
    } catch (error) {
      if (kDebugMode) {
        print('Error getting user: $error');
      }
      SnackbarHelper.showToast("服务器错误，请联系管理员~！");
    }
  }
}


